package com.happy.qademo.websheet.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.happy.qademo.websheet.common.UploadDataDto;
import com.happy.qademo.websheet.entity.WorkBookEntity;
import com.happy.qademo.websheet.entity.WorkSheetEntity;
import com.happy.qademo.websheet.repository.WorkBookRepository;
import com.happy.qademo.websheet.repository.WorkSheetRepository;
import com.happy.qademo.websheet.utils.ExcelUtils;
import com.happy.qademo.websheet.utils.SheetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Eric
 * @date 2024/07/31
 * @description
 */
@CrossOrigin(origins = "*", allowedHeaders = "*")
@Slf4j
@RestController
public class IndexController {
    @Autowired
    private WorkBookRepository workBookRepository;

    @Autowired
    private WorkSheetRepository workSheetRepository;

    @GetMapping({"index","index.html"})
    public ModelAndView index() {
        List<WorkBookEntity> all = workBookRepository.findAll();
        return new ModelAndView("index", "all", all);
    }

    @GetMapping("import")
    public ModelAndView importdata() {

        return new ModelAndView("import", "import", null);
    }

    @PostMapping("index/upload/{fileName}")
    public String createwithData(HttpServletRequest request, HttpServletResponse response, @RequestBody UploadDataDto uploadData,@PathVariable(value = "fileName") String fileName) throws IOException {
        WorkBookEntity wb = new WorkBookEntity();
        wb.setName(fileName);
        JSONObject defautOption = SheetUtil.getDefautOption();
        defautOption.put("title", fileName);
        wb.setOption(defautOption);
        Date currentDate = new Date();
        wb.setCreate_time(currentDate);
        wb.setUpdate_time(currentDate);
        workBookRepository.save(wb);
        //生成sheet数据
        log.debug("upload data:{}", JSON.toJSONString(uploadData));
        generateSheet(uploadData.getExceldatas(), wb.getId());
        return wb.getId();
    }
    @GetMapping("index/export/{wbId}")
    public void exportExcle(HttpServletRequest request, HttpServletResponse response,@PathVariable(value = "wbId") String wbId){
        Optional<WorkBookEntity> owb = workBookRepository.findById(wbId);
        if (owb.isPresent()) {
            WorkBookEntity workBookEntity = owb.get();
            List<WorkSheetEntity> workSheetEntityList = workSheetRepository.findAllBywbId(workBookEntity.getId());
            List<JSONObject> cellDatas = workSheetEntityList.stream().map(WorkSheetEntity::getData).collect(Collectors.toList());
            ExcelUtils.exportLuckySheetXlsx(JSON.toJSONString(cellDatas),workBookEntity.getName(),request,response);
        }
    }


    @GetMapping("index/create")
    public void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WorkBookEntity wb = new WorkBookEntity();

        wb.setName("default");
        wb.setOption(SheetUtil.getDefautOption());
        
        Date currentDate = new Date();
        wb.setCreate_time(currentDate);
        wb.setUpdate_time(currentDate);
        workBookRepository.save(wb);
        //生成sheet数据
        generateSheet(wb.getId());
        response.sendRedirect("/index/" + wb.getId());
    }


    @GetMapping("/index/{wbId}")
    public ModelAndView index(@PathVariable(value = "wbId") String wbId) {
        Optional<WorkBookEntity> Owb = workBookRepository.findById(wbId);
        WorkBookEntity wb = new WorkBookEntity();
        if (!Owb.isPresent()) {
            wb.setId(wbId);
            wb.setName("default");
            
            Date currentDate = new Date();
            wb.setCreate_time(currentDate);
            wb.setUpdate_time(currentDate);
            wb.setOption(SheetUtil.getDefautOption());
            // WorkBookEntity result = workBookRepository.save(wb);
            generateSheet(wbId);
        } else {
            wb = Owb.get();
        }

        return new ModelAndView("websocket", "wb", wb);
    }

    @GetMapping("delete/{wbId}")
    public Object delete(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "wbId") String wbId) throws IOException {
        Optional<WorkBookEntity> owb = workBookRepository.findById(wbId);
        if (owb.isPresent()) {
            WorkBookEntity workBookEntity = owb.get();
            List<WorkSheetEntity> workSheetEntityList = workSheetRepository.findAllBywbId(workBookEntity.getId());
            workBookRepository.deleteById(workBookEntity.getId());
            workSheetEntityList.forEach(workSheetEntity -> {
                workSheetRepository.delete(workSheetEntity);
            });
        }

        return "success";
    }

    @PostMapping("/load/{wbId}")
    public String load(@PathVariable(value = "wbId") String wbId) {

        List<WorkSheetEntity> wsList = workSheetRepository.findAllBywbId(wbId);
        List<JSONObject> list = new ArrayList<>();
        wsList.forEach(ws -> {
            list.add(ws.getData());
        });


        return JSON.toJSONString(list);
    }


    @PostMapping("/loadSheet/{wbId}")
    public String loadSheet(@PathVariable(value = "wbId") String wbId) {
        List<WorkSheetEntity> wsList = workSheetRepository.findAllBywbId(wbId);
        List<JSONObject> list = new ArrayList<>();
        wsList.forEach(ws -> {
            list.add(ws.getData());
        });
        if (!list.isEmpty()) {
            return SheetUtil.buildSheetData(list).toString();
        }
        return SheetUtil.getDefaultAllSheetData().toString();
    }

    @PostMapping("/equipment/excel/downfile")
    public void downExcelFile(@RequestParam(value = "exceldata") String exceldata,@RequestParam("fileName") String fileName,HttpServletRequest request, HttpServletResponse response) {
        //去除luckysheet中 &#xA 的换行
        exceldata = exceldata.replace("&#xA;", "\\r\\n");
        //ExcelUtils.exportLuckySheetXlsx(exceldata,"EXCEL_DOWN",request,response);
        ExcelUtils.exportLuckySheetXlsx(exceldata,fileName,request,response);
    }


    private void generateSheet(String wbId) {
        SheetUtil.getDefaultSheetData().forEach(jsonObject -> {
            WorkSheetEntity ws = new WorkSheetEntity();
            JSONObject json_data =(JSONObject) JSON.toJSON(jsonObject);
            ws.setData(json_data);
            String index = json_data.getString("index");
            ws.setIndex(index);
            int status = Integer.parseInt(json_data.get("status").toString());
            ws.setStatus(status);
            ws.setDeleteStatus(0);
            ws.setWbId(wbId);
            workSheetRepository.save(ws);
        });
    }

    private void generateSheet(List<JSONObject> sheetData, String wbId) {
        log.info("sheet data size: {}", sheetData.size());
        sheetData.forEach(jsonObject -> {
            WorkSheetEntity ws = new WorkSheetEntity();
            ws.setWbId(wbId);
            ws.setDeleteStatus(0);
            JSONObject json_data =(JSONObject) JSON.toJSON(jsonObject);
            ws.setData(json_data);
            String index = json_data.getString("index");
            ws.setIndex(index);
            // 获取 status 值
            Object statusObj = json_data.get("status");
            int status = 0; // 默认值
            if (statusObj != null) {
                String statusStr = statusObj.toString();
                try {
                    // 尝试将字符串转换为整数
                    status = Integer.parseInt(statusStr);
                } catch (NumberFormatException e) {
                    if (statusStr.equals("true")){
                        status = 1;
                    } else {
                        status = 0;
                    }
                }
            }

            // int status = Integer.parseInt(json_data.get("status").toString());


            ws.setStatus(status);
            workSheetRepository.save(ws);
        });
    }

}
